package application;

import application.thread.ServerThread;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author Simão
 */
public class ServerApplication {

    private static HashMap<Long, ServerThread> connectionMap;
    private static HashMap<Long, InetAddress> addressMap;
    private static HashMap<Long, Integer> portMap;
    private static ArrayList<Long> userList;
    /* declare the rest of the shared memory */

    public static void main(String... args) {
        ServerSocket serverSocket;
        Socket socket;
        System.out.println("DumbTalk Server Started.");
        try {
            serverSocket = new ServerSocket(8080);
        } catch (IOException ex) {
            System.out.println("IOException in ServerSocket. Aborting server.");
            return;
        }
        System.out.println("ServerSocket sucessfully initialized.");
        loadSharedMemory();
        while (true) {
            try {
                System.out.println("Server is waiting for client connection requests.");
                socket = serverSocket.accept();
            } catch (IOException ex) {
                System.out.println("IOException in Socket. Connection aborted.");
                continue;
            }
            System.out.println("Connection has been estabilished.");
            new ServerThread(socket).start();
        }
    }

    private static void loadSharedMemory() {
        connectionMap = new HashMap<>();
        addressMap = new HashMap<>();
        portMap = new HashMap<>();
        userList = new ArrayList<>();
        /* initialize the rest of the shared memory */
    }
    
    public static synchronized void addConenction(
            long userid,
            ServerThread serverThread,
            InetAddress userAddress,
            int userPort) {
        connectionMap.put(userid, serverThread);
        addressMap.put(userid, userAddress);
        portMap.put(userid, userPort);
    }
    
    public static synchronized boolean userExists(long userid) {
        return userList.contains(userid);
    }
    
    public static synchronized boolean connectionExists(long userid) {
        return connectionMap.containsKey(userid);
    }

    public static synchronized InetAddress getUserAddress(long userid) {
        return addressMap.get(userid);
    }

    public static synchronized int getUserPort(long userid) {
        return portMap.get(userid);
    }
    
    public static void sendStreamToUser(long userid, byte[] stream) {
        connectionMap.get(userid).useWriterList(ListOption.ADD,stream);
    }
    
    /* initialize the rest of the shared memory access methods */
}
